<template>
	<div @keydown="handleKeydown">
		<div class="index">
			<el-form class="elform" label-position="top" label-width="auto" :model="OrderForm" :rules="rules" size="large" ref="OrderFormRef" :disabled="route.query.type == 'detail'">
				<div class="title">订单信息</div>
				<el-row :gutter="10">
					<el-col :xs="24" :md="12" :lg="4">
						<el-form-item label="生产批号">
							<el-input class="focInput" v-model="OrderForm.order_sn" placeholder="生产批号(未填写使用默认编号)" autofocus />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :md="12" :lg="4">
						<el-form-item label="盒号">
							<el-input class="focInput" v-model="OrderForm.box_num" placeholder="请输入盒号" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :md="12" :lg="4">
						<el-form-item label="设计单号">
							<el-input class="focInput" v-model="OrderForm.design_no" placeholder="请输入设计单号" @input="handleChangeDesignNo" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :md="12" :lg="4">
						<el-form-item label="医院名称" prop="HospitalSearch">
							<el-autocomplete class="focInput" :disabled="OrderForm.design_no != ''" v-model="OrderForm.HospitalSearch" :validate-event="false" :fetch-suggestions="queryHostpital" placeholder="请输入医院名称" @select="changeHospital" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :md="12" :lg="4">
						<el-form-item label="医生姓名">
							<el-autocomplete class="focInput" v-model="OrderForm.DoctorSearch" :validate-event="false" :fetch-suggestions="queryDoctor" placeholder="请输入医生姓名" @select="DocuorSelectChange" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :md="12" :lg="4">
						<el-form-item label="患者姓名">
							<el-input class="focInput" v-model="OrderForm.name" placeholder="请输入患者姓名"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :md="12" :lg="4">
						<el-form-item label="业务员">
							<el-input class="focInput" disabled v-model="OrderForm.yw_str" placeholder="请输入业务员"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :md="12" :lg="4">
						<el-form-item label="区域">
							<el-input class="focInput" disabled v-model="OrderForm.area_str" placeholder="请输入区域"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :md="12" :lg="4">
						<el-form-item label="类型">
							<el-select class="focInput" v-model="OrderForm.type_status" placeholder="请选择类型">
								<el-option v-for="item in type" :key="item.value" :label="item.label" :value="item.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :md="12" :lg="4">
						<el-form-item label="是否试戴">
							<el-select class="focInput" v-model="OrderForm.is_try" placeholder="请选择是否试戴" @change="changeIsTry">
								<el-option v-for="item in is_try" :key="item.value" :label="item.label" :value="item.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :md="12" :lg="4">
						<el-form-item label="试戴类型" prop="try_str">
							<el-select class="focInput" v-model="OrderForm.try_str" placeholder="请选择试戴类型" :disabled="OrderForm.is_try == 0">
								<el-option v-for="item in TryTypeData" :key="item.id" :label="item.title" :value="item.id"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :md="12" :lg="4">
						<el-form-item label="锆块码">
							<el-input class="focInput" v-model="OrderForm.block_code" @change="handleBlockCode" placeholder="请输入锆块码" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :md="24" :lg="24">
						<el-form-item label="备注">
							<el-input @keydown.tab.exact.prevent="handleTab($event, 'remark')" :rows="2" type="textarea" class="focInput" v-model="OrderForm.remark" placeholder="请输入备注" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div class="productBox">
				<el-row :gutter="10">
					<el-col :xs="24" :md="12" :lg="17">
						<!-- 产品信息 -->
						<div class="title product_title">
							产品信息: {{ activeProduct?.title }}
							<div class="title_right">
								<el-input ref="form_i_14" class="focInput" data-type="14" tabindex="7" placeholder="输入产品快捷键" v-model="productKey"></el-input>
								<el-button type="primary" v-if="route.query.type != 'detail'" @click="handleTabsEdit('', 'add')">点击添加产品</el-button>
							</div>
						</div>
						<div class="editProduct">
							<template v-if="ProductDataItmes.length">
								<el-form label-position="top" label-width="auto" size="large" :model="activeProduct">
									<el-row :gutter="10">
										<el-col :xs="24" :md="12" :lg="8" v-if="GetProductFileds(activeProduct, '单冠联冠按钮') && route.query.type != 'detail'">
											<el-form-item label="是否连冠" label-position="left">
												<div class="BtnBox">
													<div
														:class="{
															singleCrown: btnindex == 0 && !activeProduct.maxillary,
															winTheChampionshipInARow: btnindex == 1 && activeProduct.maxillary
														}"
														v-for="(btnitem, btnindex) in singleCrown"
														:key="btnitem.value"
														class="BtnBox-btn"
														@click="activeProduct.maxillary = btnitem.value"
													>
														{{ btnitem.label }}
													</div>
												</div>
											</el-form-item>
										</el-col>
										<el-col :xs="24" :md="12" :lg="24">
											<el-form-item label="" class="tooth_position_box">
												<div slot="label" class="tooth_position_label">
													<div style="width: 50%">
														<p><span v-if="GetProductRules(activeProduct, '牙位')" style="color: #f56c6c">*</span>产品牙位</p>
														<input type="text" style="width: 90%" class="tooth_position_input focInput" placeholder="输入牙位快捷键 1代表上颌 2代表下颌 0代表全口" />
													</div>
													<div style="width: 50%">
														<div style="display: flex; border-bottom: 1px dashed rgba(0, 0, 0, 0.2); margin-bottom: 5px; padding-bottom: 5px">
															<input class="tooth_position_input focInput" placeholder="左上牙位快捷键" />
															<div style="border-right: 1px dashed rgba(0, 0, 0, 0.2); padding-right: 5px; margin-right: 5px"></div>
															<input class="tooth_position_input focInput" placeholder="右上牙位快捷键" />
														</div>
														<div style="display: flex">
															<input class="tooth_position_input focInput" placeholder="左下牙位快捷键" />
															<div style="border-right: 1px dashed rgba(0, 0, 0, 0.2); padding-right: 5px; margin-right: 5px"></div>
															<input class="tooth_position_input focInput" placeholder="右下牙位快捷键" />
														</div>
													</div>
												</div>
												<div>
													<lu-tooth v-if="activeProduct.uid" :key="activeProduct.uid" :tooth_position_key="activeProduct.tooth_position_key" :tooth_left_up_key="activeProduct.tooth_left_up_key" :tooth_right_up_key="activeProduct.tooth_right_up_key" :tooth_left_down_key="activeProduct.tooth_left_down_key" :tooth_right_down_key="activeProduct.tooth_right_down_key" :disabled="route.query.type == 'detail'" :maxillary="activeProduct.maxillary" :double="getToothPosition(activeProduct.multiple_crown)" :singular="getToothPosition(activeProduct.single_crown)" @change="changetooth" @update="updateKeyword"></lu-tooth>
												</div>
											</el-form-item>
										</el-col>
										<el-col :xs="24" :md="12" :lg="24" v-if="color16Data.length > 0 && GetProductFileds(activeProduct, '标准16色')">
											<el-form-item label="">
												<div slot="label" class="tooth_position_label">
													<p><span v-if="GetProductRules(activeProduct, '产品颜色')" style="color: #f56c6c">*</span>标准16色</p>
													<input type="text" class="tooth_position_input focInput" placeholder="输入颜色关键字.分割 例A.B.C" />
													<input type="text" class="tooth_position_input focInput" v-model="activeProduct.yase_remark" placeholder="" />
												</div>
												<el-checkbox-group border v-model="activeProduct.b16c">
													<el-checkbox tabindex="-1" v-for="item in color16Data" :key="item.id" :label="item.id" @change="handleYaseChange(item)">
														{{ item.title }}
														<span v-if="item.key_word">({{ item.key_word }})</span>
													</el-checkbox>
												</el-checkbox-group>
											</el-form-item>
										</el-col>
										<el-col :xs="24" :md="12" :lg="24" v-if="color26Data.length > 0 && GetProductFileds(activeProduct, '标准26色')">
											<el-form-item>
												<div slot="label" class="tooth_position_label">
													<p><span v-if="GetProductRules(activeProduct, '产品颜色')" style="color: #f56c6c">*</span>标准26色</p>
												</div>
												<el-checkbox-group border v-model="activeProduct.b26c">
													<el-checkbox tabindex="-1" v-for="item in color26Data" :key="item.id" :label="item.id" @change="handleYaseChange(item)">
														{{ item.title }}
														<span v-if="item.key_word">({{ item.key_word }})</span>
													</el-checkbox>
												</el-checkbox-group>
											</el-form-item>
										</el-col>
										<el-col :xs="24" :md="12" :lg="24" v-if="abutmentColor.length > 0 && GetProductFileds(activeProduct, '基牙牙色')">
											<el-form-item>
												<div slot="label" class="tooth_position_label">
													<p><span v-if="GetProductRules(activeProduct, '产品颜色')" style="color: #f56c6c">*</span>基牙牙色</p>
												</div>
												<el-checkbox-group border v-model="activeProduct.jbys">
													<el-checkbox tabindex="-1" v-for="item in abutmentColor" :key="item.id" :label="item.id" @change="handleYaseChange(item)">
														{{ item.title }}
														<span v-if="item.key_word">({{ item.key_word }})</span>
													</el-checkbox>
												</el-checkbox-group>
											</el-form-item>
										</el-col>
										<el-col :xs="24" :md="12" :lg="24" v-if="resinToothColorimetry.length > 0 && GetProductFileds(activeProduct, '树脂牙比色')">
											<el-form-item>
												<div slot="label" class="tooth_position_label">
													<p><span v-if="GetProductRules(activeProduct, '产品颜色')" style="color: #f56c6c">*</span>树脂牙比色</p>
												</div>
												<el-checkbox-group border v-model="activeProduct.szybs">
													<el-checkbox tabindex="-1" v-for="item in resinToothColorimetry" :key="item.id" :label="item.id" @change="handleYaseChange(item)">
														{{ item.title }}
														<span v-if="item.key_word">({{ item.key_word }})</span>
													</el-checkbox>
												</el-checkbox-group>
											</el-form-item>
										</el-col>
										<el-col :xs="24" :md="12" :lg="24" v-if="positionRequire.length > 0 && GetProductFileds(activeProduct, '就位要求')">
											<el-form-item>
												<div slot="label" class="tooth_position_label">
													<p><span v-if="GetProductRules(activeProduct, '设计要求')" style="color: #f56c6c">*</span>就位要求</p>
												</div>
												<el-checkbox-group border v-model="activeProduct.jwyq">
													<el-checkbox class="focInput" v-for="item in positionRequire" :key="item.id" :value="item.id">{{ item.title }}</el-checkbox>
												</el-checkbox-group>
											</el-form-item>
										</el-col>
										<el-col :xs="24" :md="12" :lg="24" v-if="biteRequire.length > 0 && GetProductFileds(activeProduct, '咬颌要求')">
											<el-form-item>
												<div slot="label" class="tooth_position_label">
													<p><span v-if="GetProductRules(activeProduct, '设计要求')" style="color: #f56c6c">*</span>咬颌要求</p>
												</div>
												<el-checkbox-group border v-model="activeProduct.yhyq">
													<el-checkbox class="focInput" v-for="item in biteRequire" :key="item.id" :value="item.id">{{ item.title }}</el-checkbox>
												</el-checkbox-group>
											</el-form-item>
										</el-col>
										<el-col :xs="24" :md="12" :lg="24" v-if="neckRequire.length > 0 && GetProductFileds(activeProduct, '颈缘要求')">
											<el-form-item>
												<div slot="label" class="tooth_position_label">
													<p><span v-if="GetProductRules(activeProduct, '设计要求')" style="color: #f56c6c">*</span>颈缘要求</p>
												</div>
												<el-checkbox-group border v-model="activeProduct.jyyq">
													<el-checkbox class="focInput" v-for="item in neckRequire" :key="item.id" :value="item.id">{{ item.title }}</el-checkbox>
												</el-checkbox-group>
											</el-form-item>
										</el-col>
										<el-col :xs="24" :md="12" :lg="24" v-if="GetProductFileds(activeProduct, '牙色照片')">
											<el-form-item label="牙色照片">
												<div class="productBox-itemimages">
													<div class="productBox-itemimages-img" @click.stop v-for="(i, k) in activeProduct.images" :key="i">
														<el-image :src="i" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="activeProduct.images" :initial-index="k" class="productBox-itemimages-img" fit="cover" />
														<el-button v-if="route.query.type != 'detail'" class="deleteicon flexstart" type="danger" :icon="Delete" circle @click.stop="activeProduct.images.splice(k, 1)" />
													</div>
													<el-upload class="colorUpload" v-if="route.query.type != 'detail'" multiple drag action="https://up-z2.qiniup.com" :data="ProductUploadParams" :before-upload="SendQiniuToken" :on-success="ProductUploadSuccess" accept="image/*" :show-file-list="false" list-type="picture-card">
														<el-icon><Plus /></el-icon>
													</el-upload>
												</div>
											</el-form-item>
										</el-col>
									</el-row>
								</el-form>
							</template>

							<div class="emptybox" v-if="ProductDataItmes.length == 0" @click="handleProduct">
								<img draggable="false" class="emptybox-icon" src="@/assets/images/empty.png" />
								<div class="emptybox-text">点击添加第一个产品吧~</div>
							</div>
						</div>

						<div class="product_list">
							<div class="header">
								<div class="num">数量</div>
								<div class="type">义齿类型</div>
								<div class="yawei">牙位</div>
								<div class="yase">牙色</div>
								<div class="yaoqiu">要求</div>
								<div class="yaseimg">牙色照片</div>
								<div class="jiage">价格（元）</div>
							</div>
							<div class="product_list_c">
								<div
									:class="{ product_list_content_active: index == tabsActiveName }"
									class="product_list_content"
									v-for="(item, index) in ProductDataItmes"
									:key="item.id"
									@click="
										tabsActiveName = index;
										activeProduct = ProductDataItmes[tabsActiveName];
									"
								>
									<div class="num">{{ item.num }}</div>
									<div class="type">{{ item.title }}</div>
									<div class="yawei">
										<tooth1 :single_crown="item.single_crown" :multiple_crown="item.multiple_crown"></tooth1>
									</div>
									<div class="yase">
										<!-- <p v-if="item.b16c.length">标准16色:{{ getStrYase(1) }}</p>
										<p v-if="item.b26c.length">标准26色:{{ getStrYase(2) }}</p>
										<p v-if="item.jbys.length">基牙牙色:{{ getStrYase(3) }}</p>
										<p v-if="item.szybs.length">树脂牙比色：{{ getStrYase(4) }}</p> -->
										<p v-if="item.yase_remark">{{ item.yase_remark }}</p>
									</div>
									<div class="yaoqiu">
										<p v-if="item.jwyq.length">就位要求:{{ positionRequire.filter((it) => it.id == item.jwyq[0])[0].title }}</p>
										<p v-if="item.yhyq.length">咬颌要求:{{ biteRequire.filter((it) => it.id == item.yhyq[0])[0].title }}</p>
										<p v-if="item.jyyq.length">颈缘要求:{{ neckRequire.filter((it) => it.id == item.jyyq[0])[0].title }}</p>
									</div>
									<div class="yaseimg">
										<div @click.stop v-for="(i, k) in item.images" :key="i">
											<el-image style="width: 50px; height: 50px" :src="i" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="item.images" :initial-index="k" class="productBox-itemimages-img" fit="cover" />
										</div>
									</div>
									<div class="jiage">{{ (item.num * item.price).toFixed(2) }}</div>
									<el-icon class="del" v-if="route.query.type != 'detail'" size="20" color="#F56C6C" @click.stop="handleTabsEdit(index, 'delete')"><Close /></el-icon>
								</div>
							</div>
						</div>
					</el-col>
					<el-col :xs="24" :md="12" :lg="7">
						<div class="title">附件信息</div>
						<el-tabs v-model="attachment">
							<el-tab-pane native v-for="item in attachmentRequire" :key="item.id" :label="item.title" :name="item.id">
								<el-form label-position="top" label-width="auto" :model="item" size="large" ref="attachmentFormRef">
									<el-row :gutter="10">
										<el-col :xs="24" :md="12" :lg="24">
											<el-form-item :label="detailitem.title" label-position="left" v-for="(detailitem, index) in item.detailList" :key="index">
												<el-input-number class="inputNumber" v-model="detailitem.num" :min="0" />
											</el-form-item>
										</el-col>
										<el-col :xs="24" :md="24" :lg="24">
											<div class="uploadfile">
												<div class="title">随单附件</div>
												<el-upload tabindex="-1" class="supload" v-if="route.query.type != 'detail'" drag action="https://up-z2.qiniup.com" :data="ProductUploadParams" :before-upload="beforeUpload" :on-success="attachmentUploadSuccess" multiple :show-file-list="false">
													<el-icon size="24"><Plus /></el-icon>
												</el-upload>
												<template v-if="uploadFileList.length > 0">
													<div class="productBoxlist" v-for="(item, index) in uploadFileList">
														<div class="productBoxlist-left">
															<el-image class="productBoxlist-img" v-if="/^image\/.+$/.test(item.type)" :src="item.url" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[item.url]" fit="cover" />
															<div class="productBoxlist-type" v-else>
																<el-icon size="35"><FolderOpened /></el-icon>
															</div>
															<div class="productBoxlist-info">
																<div>{{ item.name }}</div>
																<div>{{ `${formatBytes(item.size)}` }}</div>
															</div>
														</div>
														<div v-if="route.query.type != 'detail'" class="productBoxlist-right" @click="removeFile(item, index)">
															<el-icon size="20"><Close /></el-icon>
														</div>
														<div v-if="route.query.type == 'detail' && /\.stl$/i.test(item.name)" class="productBoxlist-right" style="margin-right: 10px" @click="handlestlPreview(item)">
															<el-icon size="20"><View /></el-icon>查看
														</div>
														<div v-if="route.query.type == 'detail' && !/^image\/.+$/.test(item.type)" class="productBoxlist-right" @click="fileDownload(item.url, item.name)">
															<el-icon size="20"><Download /></el-icon>
														</div>
													</div>
												</template>
												<div v-if="uploadFileList.length == 0 && route.query.type == 'detail'" class="emptybox" style="margin-top: 10px">
													<img draggable="false" class="emptybox-icon" src="@/assets/images/empty.png" />
													<div class="emptybox-text">暂无附件</div>
												</div>
											</div>
										</el-col>
									</el-row>
								</el-form>
							</el-tab-pane>
						</el-tabs>

						<div class="title">客户习惯</div>
						<div>
							<el-input @keydown.tab.exact.prevent="handleTab($event, 'remark2')" v-model="OrderForm.remark2" :rows="6" type="textarea" placeholder="请输入客户习惯" />
						</div>
					</el-col>
				</el-row>
			</div>
		</div>
		<div class="sumbit" v-if="route.query.type != 'detail'">
			<el-button class="sumbit-btn focInput" data-type="18" type="primary" @keydown.enter="route.query.type == 'update' ? updateFormAndPrint() : sumbitAndPrint()" @click="route.query.type == 'update' ? updateFormAndPrint() : sumbitAndPrint()">{{ route.query.type == 'update' ? '修改及打印' : '提交及打印' }}</el-button>
			<el-button class="sumbit-btn focInput" data-type="17" type="primary" @keydown.enter="route.query.type == 'update' ? updateForm() : sumbit()" @click="route.query.type == 'update' ? updateForm() : sumbit()">{{ route.query.type == 'update' ? '修改' : '提交' }}</el-button>
			<el-button ref="form_i_15" class="sumbit-btn" @click="router.go(-1)" v-if="route.query.type != 'detail'">取消</el-button>
		</div>
	</div>
	<!-- 新增产品 -->
	<el-dialog title="新增产品" style="border-radius: 10px" v-model="newProducts" draggable>
		<div class="dialogsearch">
			<el-input @keydown="handleDialogInputKeydown" v-if="newProducts" ref="dialogInput" v-model="productSearchKey" style="width: 300px" size="large" placeholder="请输入产品名称" prefix-icon="Search" @input="searchProduct('')" />
			<el-button type="primary" size="large" @click="searchProduct('')">搜索</el-button>
		</div>
		<div class="productdialog">
			<div class="productdialog-left">
				<el-menu style="width: 200px; min-height: 100%" unique-opened @select="searchProduct">
					<el-sub-menu v-for="(item, index) in ProductTypeData" :key="index" :index="String(item.id)">
						<template #title>
							<el-icon><Menu /></el-icon>
							<span>{{ item.title }}</span>
						</template>
						<el-menu-item v-for="(subItem, subIndex) in item.child" :key="subIndex" :index="String(subItem.id)">
							<el-icon><StarFilled /></el-icon>
							<span>{{ subItem.title }}</span>
						</el-menu-item>
					</el-sub-menu>
				</el-menu>
			</div>
			<div class="productdialog-right" @keydown="handleRadioKeydown">
				<el-radio-group v-model="productValue" v-if="ProductData.length">
					<el-radio v-for="(item, index) in ProductData" :key="item.id" :value="JSON.stringify(item)" size="large" border :ref="(el) => setRadioRef(el, index)">{{ item.title }}</el-radio>
				</el-radio-group>
				<div class="emptybox" v-else>
					<img draggable="false" class="emptybox-icon" src="@/assets/images/empty.png" />
					<div class="emptybox-text">此类型暂无产品~</div>
				</div>
			</div>
		</div>
		<span slot="footer" class="productdialog-footer" v-if="ProductData.length">
			<el-button @click="newProducts = false">取 消</el-button>
			<el-button type="primary" @click="addProduct">确 定</el-button>
		</span>
	</el-dialog>

	<!-- 打印配置 -->
	<el-dialog title="打印配置" style="border-radius: 10px" v-model="printDialogVisible" draggable @open="init">
		<div class="selectbox">
			<div class="selectbox-left">
				<div class="printer" v-for="item in printerNameList" :class="{ activeprinter: printerName == item.id }" :key="item.name" @click="selectPrinterType(item)">
					<img :src="item.icon" class="icon" />
					<div class="title">{{ item.name }}</div>
				</div>
			</div>
			<div class="selectbox-right">
				<div class="rightbox">
					<div class="printercard" :class="{ active: item.name == selectprinter }" v-for="item in printList" :key="item.name" @click="printerSelect(item)">
						<img v-if="item.name == selectprinter" class="icon" src="@/assets/icon/printer.png" />
						<div class="printercard-item">{{ item.name }}</div>
					</div>
				</div>
			</div>
		</div>
		<el-footer style="display: flex; align-items: center; justify-content: flex-end">
			<el-button type="primary" @click="handlePrint">确定</el-button>
		</el-footer>
	</el-dialog>

	<!-- 预览stl文件 -->
	<stlPreview ref="stlPreviewRef"></stlPreview>

	<!-- 本地打印 -->
	<!-- <component is="prPage" ref="componentRef" class="compo"></component> -->
	<component is="locationPrint" ref="componentRef" class="compo"></component>
</template>
<script setup>
	import { ref, reactive, onMounted, watch, computed, nextTick } from 'vue';
	import { useRoute, useRouter } from 'vue-router';
	import { ElMessage, ElMessageBox } from 'element-plus';
	import { Close, Plus, Menu, StarFilled, Delete } from '@element-plus/icons-vue';
	import { getHabit, getSalesmanList, getDesignToHospital, sumbitform, getOrderDetailData, getHospitalListData, getDoctorListData, addDoctorData, getTryType, SendGetProductType, getProductList, getToothColor, getDesignRequire, getAttachmentRequire, getAttachmentRequireDetail, SendUpdateForm, getProductKeyList } from '@/api/PlaceOrder';
	import { getQiniuToken } from '@/api/Public';
	import { separateAdjacentAndNonAdjacent, formatBytes, toothConversion, groupConsecutiveNumbers, fileDownload } from '@/utils/PlaceOrder';
	import { debounce } from 'lodash-es';
	import stlPreview from '@/components/stlPreview/index.vue';
	import { usePrintStore } from '@/store/print';

	const route = useRoute();
	const router = useRouter();
	const printStore = usePrintStore();

	// 基本信息表单
	const OrderForm = ref({
		order_sn: '', //生产批号
		order_sn1: '', //记录老的批号 修改时使用
		box_num: '', //盒号
		design_no: '', //设计单号
		HospitalSearch: '', //医院名称
		hospital_id: '', //医院id
		DoctorSearch: '', //医生名称
		doc_user_id: '', //医生id
		name: '', //患者姓名
		area_str: '', //区域名称
		yw_str: '', //业务名称
		type_status: 1, //类型
		is_try: 0, //是否试戴
		try_str: '', //试戴类型
		user_id: '', //登录者id
		block_code: '', //铅块码
		remark: '', //备注
		remark2: '', //客户习惯
		order_type: 1,
		is_check_in: 1
	});

	//打印组件实例
	const componentRef = ref('');

	// 基础信息表单ref
	const OrderFormRef = ref('');

	// 基本信息表单校验
	const rules = reactive({
		HospitalSearch: [{ required: true, message: '请选择医院', trigger: ['change', 'blur'] }]
	});

	//设计单号带出医院
	const handleChangeDesignNo = debounce(async () => {
		if (!OrderForm.value.design_no) return;

		const res = await getDesignToHospital({ design_no: OrderForm.value.design_no });
		if (res.data) {
			OrderForm.value.HospitalSearch = res.data.hospital_info.title;
			OrderForm.value.hospital_id = res.data.hospital_info.id;
			getAreaAndYw(res.data.hospital_info);
		} else {
			ElMessage.error('此设计单号不存在医院');
		}
	}, 500);

	//监听设计单号 没有设计单号清除医院 医院id
	watch(
		() => OrderForm.value.design_no,
		(val) => {
			if (!val) {
				OrderForm.value.hospital_id = '';
				OrderForm.value.HospitalSearch = '';
			}
		}
	);

	// 搜索医院事件
	const queryHostpital = async (queryString, cb) => {
		const res = await getHospitalListData({
			key: queryString,
			order_type: 1
		});
		if (res.data.length) {
			cb(
				res.data.map((item) => {
					return { ...item, value: item.title };
				})
			);
		}
		if (res.data.length == 0) return cb([]);
	};

	// 医院选中事件
	const changeHospital = (data) => {
		//医院id
		OrderForm.value.hospital_id = data.id;
		console.log(data.id);

		getAreaAndYw(data);
	};

	//查询业务员 区域
	const getAreaAndYw = async (data) => {
		//查询业务员和区域 直接回显
		const res = await getSalesmanList({
			area_id: data.company_area_id
		});
		if (res.data) {
			//区域
			OrderForm.value.area_str = res.data.area.title;
			//业务员
			OrderForm.value.yw_str = res.data.user.nickname;
		}
	};

	// 监听医院名称输入框当有变化时清空医生输入框
	watch(
		() => OrderForm.value.HospitalSearch,
		(val) => {
			// 清空 医院id 业务员 区域
			if (!val) {
				OrderForm.value.hospital_id = '';
				OrderForm.value.area_str = '';
				OrderForm.value.yw_str = '';
			}

			if (isMounted.value || !route.query.type) {
				//清空医院名称 医院id
				OrderForm.value.DoctorSearch = '';
				OrderForm.value.doc_user_id = '';
			}
		}
	);

	// 搜索医生事件
	const queryDoctor = async (queryString, cb) => {
		if (!OrderForm.value.hospital_id) return cb([]), ElMessage.error('请先选择医院');
		const res = await getDoctorListData({ hospital_id: OrderForm.value.hospital_id, key: queryString });
		if (res.data.length == 0) return cb([{ value: queryString, type: 'add' }]);
		cb(
			res.data.map((item) => {
				return { ...item, value: item.nickname };
			})
		);
	};

	// 医生下拉选择事件
	const DocuorSelectChange = (data) => {
		if (!data.type) return (OrderForm.value.doc_user_id = data.id);
		if (data.type == 'add') {
			ElMessageBox.confirm('是否新增医生', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				const res = await addDoctorData({ hospital_id: OrderForm.value.hospital_id, nickname: data.value });
				if (res) {
					ElMessage.success('新增成功');
					OrderForm.value.doc_user_id = res.data.id;
				}
			});
		}
	};

	// 监听医生输入框当有变化时清空hospital_son_doctor_id
	watch(
		() => OrderForm.value.DoctorSearch,
		(val) => {
			if (!val) OrderForm.value.doc_user_id = '';
		}
	);

	// 类型
	const type = reactive([
		{ label: '新做', value: 1 },
		{ label: '返修', value: 2 },
		{ label: '重做', value: 3 }
	]);

	// 是否试戴
	const is_try = reactive([
		{ label: '是', value: 1 },
		{ label: '否', value: 0 }
	]);

	// 是否试戴
	const changeIsTry = (data) => {
		if (data == 0) OrderForm.value.try_str = '';
		if (data == 1) {
			getTry_strData();
		}
	};

	//试戴类型列表
	const TryTypeData = ref([]);
	//获取试戴类型数据
	const getTry_strData = async () => {
		let res = await getTryType();
		TryTypeData.value = res.data;
	};

	// 监听类型是否是返修 如果是 把内容填充到备注中
	watch(
		() => OrderForm.value.type_status,
		() => {
			if (!isMounted.value && route.query.type) return;

			if (OrderForm.value.type_status == 2) {
				OrderForm.value.remark = OrderForm.value.remark + '返修';
			} else {
				//找出备注中为返修的字符串
				let index = OrderForm.value.remark.indexOf('返修');
				if (index != -1) {
					OrderForm.value.remark = OrderForm.value.remark.replace('返修', '');
				}
			}
		}
	);

	//备份一下老的试戴类型
	let oldTryType = ref('');

	//监听是否有试戴类型 把内容填充到备注中
	watch(
		() => OrderForm.value.try_str,
		() => {
			if (!isMounted.value && route.query.type) return;
			//如果有老的 试戴类型 删除老的试戴类型 或者没选择试戴类型
			if (oldTryType.value || !OrderForm.value.try_str) {
				let oldTryTypeList = TryTypeData.value.filter((item) => item.id == oldTryType.value);
				if (oldTryTypeList.length > 0) {
					OrderForm.value.remark = OrderForm.value.remark.replace(oldTryTypeList[0].title, '');
				}
			}
			if (OrderForm.value.is_try) {
				//在TryTypeData.value 中筛选出试戴类型
				let tryType = TryTypeData.value.filter((item) => item.id == OrderForm.value.try_str);
				if (tryType.length > 0) {
					//添加到备注中
					OrderForm.value.remark = OrderForm.value.remark + tryType[0].title;
					//记录这次的试戴类型
					oldTryType.value = tryType[0].id;
				}
			}
		}
	);

	//锆快码发生变化时回车时 执行
	const handleBlockCode = async () => {
		//更新表单
		// updateForm();
	};

	// 是否显示产品弹窗
	const newProducts = ref(false);

	// 打开新增产品弹窗
	const handleProduct = () => {
		//没有选择医院 提示先选择医院
		if (!OrderForm.value.hospital_id) return ElMessage.error('请先选择医院');
		newProducts.value = true;
		DialogOpen();
	};

	// 产品类别
	const ProductTypeData = ref([]);

	//产品弹窗输入框实例
	const dialogInput = ref('');
	// 弹窗打开回调
	const DialogOpen = async () => {
		// 清空产品类别列表
		ProductTypeData.value = [];
		//清空产品列表
		ProductData.value = [];

		//给输入框设置焦点
		nextTick(() => {
			setTimeout(() => {
				dialogInput.value.focus();
			}, 500);
		});
		// 清空产品(单选框)绑定的值
		productValue.value = '';

		const res = await SendGetProductType({ hospital_id: OrderForm.value.hospital_id, pid: '' });
		if (res.data.length) {
			ProductTypeData.value = res.data;
			ProductTypeData.value.forEach(async (item) => {
				const result = await SendGetProductType({ hospital_id: OrderForm.value.hospital_id, pid: item.id });
				if (result) {
					item.child = result.data;
				}
			});
		}
	};

	//产品列表
	const ProductData = ref([]);

	// 产品列表搜索key
	const productSearchKey = ref('');

	//产品列表搜索
	const searchProduct = debounce(async (id = '') => {
		let res = await getProductList({ product_type_id: id, key: productSearchKey.value, hospital_id: OrderForm.value.hospital_id });
		ProductData.value = res.data;
	}, 500);

	// 选中产品列表表单
	const ProductDataItmes = ref([]);

	// 当前的产品项
	const activeProduct = ref('');

	// 当前tabs激活的标签页
	const tabsActiveName = ref(0);

	// 产品绑定的值
	const productValue = ref('');

	// 弹窗-确认事件
	const addProduct = () => {
		if (!productValue.value) return ElMessage.error('请先选择产品');
		const data = JSON.parse(productValue.value);
		//处理选择的数据
		addProductDataItmes(data);

		//关闭弹窗
		newProducts.value = false;

		//清空弹窗搜索字段 列表数据 选择的产品
		productValue.value = '';
		ProductData.value = [];
		productKey.value = '';

		//输入框聚焦到产品牙位输入框上
		nextTick(() => {
			let nodeList = document.querySelectorAll('.focInput'); // 获取所有具有 'focInput' 类的输入框
			let nodeArray = Array.from(nodeList); // 将 NodeList 转换为数组
			let nextIndex = 14;
			// 如果找到下一个输入框，则聚焦
			if (nodeArray[nextIndex]) {
				// 移动到下一个输入框
				nodeArray[nextIndex].focus();
			}
		});
	};

	//产品快捷键
	const productKey = ref('');

	//监听产品快捷键输入 查找产品
	const productKeyChange = async (e) => {
		//没有选择医院 提示先选择医院
		if (!OrderForm.value.hospital_id) return ElMessage.error('请先选择医院');

		if (!productKey.value) return;

		//校验上个产品是否填写完毕
		let vv = productSingleVerification();
		if (!vv) {
			return;
		}

		//查找项
		let res = await getProductKeyList({
			page: 1,
			pagesize: 1000,
			key_word: productKey.value,
			hospital_id: OrderForm.value.hospital_id
		});

		if (!res.data.data.length) {
			ElMessage.error('没有查询到相关产品');
			return;
		}

		if (res.data.length == 0) {
			ElMessage.error('没有查询到相关产品');
			return;
		}

		//处理选择的数据
		addProductDataItmes(res.data.data[0]);

		productKey.value = '';
	};

	//处理选择的数据
	const addProductDataItmes = (data) => {
		//判断data是否在ProductDataItmes.value中 存在则不能添加
		let isExist = ProductDataItmes.value.find((item) => item.id == data.id);
		if (isExist) {
			ElMessage.error('已添加此产品');
			return;
		}

		let data1 = {
			...data,
			maxillary: false, //单冠 双冠
			images: [], //牙色图片列表
			num: '', //数量
			tooth_position_key: '', //产品牙位输入框快捷键
			tooth_left_up_key: '', //产品牙位左上快捷键
			tooth_left_down_key: '', //产品牙位左下快捷键
			tooth_right_up_key: '', //产品牙位右上快捷键
			tooth_right_down_key: '', //产品牙位右下快捷键
			yase_key: '', //牙色输入框快捷键
			yase_remark: '', //牙色备注
			single_crown: '', //选择的单冠
			multiple_crown: '', //选择的连冠
			b16c: [],
			b26c: [],
			jbys: [],
			szybs: [],
			jwyq: [],
			yhyq: [],
			jyyq: [],
			//生成唯一值
			uid: Date.now().toString(36) + Math.random().toString(36).substr(2)
		};

		ProductDataItmes.value.unshift(data1);

		activeProduct.value = data1;
	};

	// 设置隐藏字段
	const GetProductFileds = (item, text) => {
		return item.hidedata_text ? item.hidedata_text.split(',').includes(text) : false;
	};

	// 设置必须校验的字段
	const GetProductRules = computed(() => {
		return (item, text) => {
			return item.choosedata_text.split(',').includes(text);
		};
	});

	// 产品集合点击编辑 删除
	const handleTabsEdit = async (index, action) => {
		if (action == 'add') {
			//没有选择医院 提示先选择医院
			if (!OrderForm.value.hospital_id) return ElMessage.error('请先选择医院');
			//校验必填
			newProducts.value = productSingleVerification();
			DialogOpen();

			return (productSearchKey.value = '');
		}
		ProductDataItmes.value.splice(index, 1);
		tabsActiveName.value = index == 0 ? 0 : index - 1;
		activeProduct.value = ProductDataItmes.value[tabsActiveName.value];
	};

	// 单冠/连冠
	const singleCrown = reactive([
		{ label: '单冠', value: false },
		{ label: '连冠', value: true }
	]);

	// 格式化牙位数据
	const getToothPosition = computed(() => {
		return (tooths) => {
			return tooths ? tooths.split(',').map((item) => Number(item)) : [];
		};
	});

	/** 牙位点击事件 */
	const changetooth = (res) => {
		let { singular, double } = res;

		const { adjacent, nonAdjacent } = separateAdjacentAndNonAdjacent(double);
		singular = singular.concat(nonAdjacent);

		// 把单冠和非相邻的双冠合并，然后过滤掉空值，转成字符串
		activeProduct.value.single_crown = singular.filter(Boolean).join(',');

		// 把相邻的双冠过滤掉空值，转成字符串
		activeProduct.value.multiple_crown = adjacent.filter(Boolean).join(',');

		if (singular.length == 0 || JSON.stringify(singular) == '[null]') {
			return;
		}

		// 如果单冠和双冠都没有则不处理
		if (!activeProduct.value.single_crown && !activeProduct.value.multiple_crown) return;

		// 把单冠和双冠的值都取出来，存一起
		const crown = [...stringtoArray(activeProduct.value.single_crown), ...stringtoArray(activeProduct.value.multiple_crown)].filter(Boolean);
		// 处理牙齿数量赋值逻辑 根据production_unit 字段判断 1 是个 2是 颗 如果是颗 单冠和 双冠相加 取总数 如果是个 上颚和下颚 有多个都算1个
		let num = 0;

		// 个
		if (activeProduct.value?.production_unit === 1) {
			// 上颚和下颚的分组
			const top = crown.filter((item) => item >= 11 && item <= 28);
			const bottom = crown.filter((item) => item >= 31 && item <= 48);

			// 判断上颚和下颚的数量
			if (top.length || bottom.length) {
				num = top.length && bottom.length ? 2 : 1;
			}
		}

		// 颗
		if (activeProduct.value?.production_unit === 2) {
			// 单冠和双冠相加，取总数
			num = crown.length;
		}

		// 赋值牙齿数量
		activeProduct.value.num = num;
	};

	/** 快捷键事件 */
	const updateKeyword = (e) => {
		if (e == 5) {
			activeProduct.value.tooth_position_key = '';
		}
		if (e == 1) {
			activeProduct.value.tooth_left_up_key = '';
		}
		if (e == 2) {
			activeProduct.value.tooth_right_up_key = '';
		}
		if (e == 3) {
			activeProduct.value.tooth_right_down_key = '';
		}
		if (e == 4) {
			activeProduct.value.tooth_left_down_key = '';
		}
	};

	//标准16色
	const color16Data = ref([]);
	//获取标准16色列表
	const getColor16Data = async () => {
		let res = await getToothColor({ yase_cate_id: 1, is_key_word: 1 });
		color16Data.value = res.data;
	};

	//标准26色
	const color26Data = ref([]);
	//获取标准26色列表
	const getColor26Data = async () => {
		let res = await getToothColor({ yase_cate_id: 2, is_key_word: 1 });
		color26Data.value = res.data;
	};

	//基牙牙色
	const abutmentColor = ref([]);
	//获取基牙牙色列表
	const getAbutmentColor = async () => {
		let res = await getToothColor({ yase_cate_id: 3, is_key_word: 1 });
		abutmentColor.value = res.data;
	};

	//树脂牙比色
	const resinToothColorimetry = ref([]);
	//获取树脂牙比色列表
	const getResinToothColorimetry = async () => {
		let res = await getToothColor({ yase_cate_id: 4, is_key_word: 1 });
		resinToothColorimetry.value = res.data;
	};

	//鼠标点击牙色选择事件
	const handleYaseChange = (val) => {
		//先判断是否有activeProduct.value.yase_remark 中是否有内容
		if (activeProduct.value.yase_remark.includes(val.title)) {
			//替换为空
			//如果当前内容的前一位是, 则连,+内容一起替换为空 否则 只替换内容
			if (activeProduct.value.yase_remark[activeProduct.value.yase_remark.indexOf(val.title) + val.title.length] == ',') {
				activeProduct.value.yase_remark = activeProduct.value.yase_remark.replace(val.title + ',', '');
			} else {
				activeProduct.value.yase_remark = activeProduct.value.yase_remark.replace(val.title, '');
			}
		} else {
			//添加
			if (activeProduct.value.yase_remark) {
				activeProduct.value.yase_remark = activeProduct.value.yase_remark + ',' + val.title;
			} else {
				activeProduct.value.yase_remark = val.title;
			}
		}
	};

	//返回对应的牙色字符串
	// const getStrYase = (val) => {
	// 	// 定义数据映射关系
	// 	const dataMapping = {
	// 		1: { dataArray: color16Data.value, key: 'b16c' },
	// 		2: { dataArray: color26Data.value, key: 'b26c' },
	// 		3: { dataArray: abutmentColor.value, key: 'jbys' },
	// 		4: { dataArray: resinToothColorimetry.value, key: 'szybs' }
	// 	};

	// 	let nkey = dataMapping[val]?.key;
	// 	let str = [];
	// 	//循环对应的数组
	// 	activeProduct.value[nkey].forEach((item) => {
	// 		dataMapping[val].dataArray.forEach((it) => {
	// 			if (item == it.id) {
	// 				str.push(it.title);
	// 			}
	// 		});
	// 	});

	// 	return str.join(',');
	// };

	//牙色快捷键
	const handleYaseKeyChange = debounce(async (item) => {
		// 验证输入
		if (!item || !item.yase_key) return;

		try {
			// 获取牙色数据
			const res = await getToothColor({ key_word: item.yase_key, is_key_word: 1 });

			// 处理响应数据
			if (res?.data?.length) {
				// 定义数据映射关系
				const dataMapping = {
					1: { dataArray: color16Data.value, key: 'b16c' },
					2: { dataArray: color26Data.value, key: 'b26c' },
					3: { dataArray: abutmentColor.value, key: 'jbys' },
					4: { dataArray: resinToothColorimetry.value, key: 'szybs' }
				};

				// 处理每个数据项
				res.data.forEach((it) => {
					const category = dataMapping[it.yase_cate_id];

					// 验证数据分类
					if (!category) return;

					// 如果key_word为空且数据不存在，则添加到对应数组
					if ((it.key_word === '' || it.key_word === null) && category.dataArray.every((item) => item.id !== it.id)) {
						category.dataArray.push(it);
					}

					// 如果id不存在于目标数组中，则添加
					if (item[category.key] && !item[category.key].includes(it.id)) {
						item[category.key].push(it.id);
						//把每个数据项都取出来，存一起
						if (item.yase_remark) {
							item.yase_remark = item.yase_remark + ',' + it.title;
						} else {
							item.yase_remark = it.title;
						}
					}

					//清除输入框
					item.yase_key = '';
				});
			} else {
				// 显示无数据提示
				ElMessage.error('暂无相关绑定牙色');
			}
		} catch (error) {
			// 错误处理
			ElMessage.error('获取牙色数据失败，请稍后重试');
		}
	}, 500);

	//就位要求
	const positionRequire = ref([]);
	//获取就位要求列表
	const getPositionRequire = async () => {
		let res = await getDesignRequire({ yaoqiu_cate_id: 1 });
		positionRequire.value = res.data;
	};

	//咬颌要求
	const biteRequire = ref([]);
	//获取咬颌要求列表
	const getBiteMouthRequire = async () => {
		let res = await getDesignRequire({ yaoqiu_cate_id: 2 });
		biteRequire.value = res.data;
	};

	//颈缘要求
	const neckRequire = ref([]);
	//获取颈缘要求列表
	const getNeckRequire = async () => {
		let res = await getDesignRequire({ yaoqiu_cate_id: 3 });
		neckRequire.value = res.data;
	};

	//点击添加产品时单个校验
	const productSingleVerification = () => {
		//如果没有产品 第一次添加 不用校验
		if (ProductDataItmes.value.length == 0) {
			return true;
		}
		//获取要校验的内容
		let verificationList = activeProduct.value.choosedata_text ? activeProduct.value.choosedata_text.split(',') : [];

		//获取需要校验内容对应的字段
		let hidedata_textList = activeProduct.value.hidedata_text ? activeProduct.value.hidedata_text.split(',') : [];

		//如果要校验的内容是空的 不需要校验
		if (verificationList.length == 0) {
			return true;
		}

		//提示字符串
		let errorStr = '';

		//verificationList中有牙位  校验牙位
		if (verificationList.includes('牙位')) {
			//没有选择牙位 提示
			if (!activeProduct.value.single_crown && !activeProduct.value.multiple_crown) {
				//将提示内容 添加到提示字符串中
				errorStr = errorStr + '请选择牙位<br/>';
			}
		}

		//verificationList中有  校验产品颜色
		if (verificationList.includes('产品颜色')) {
			//如果包含十六色 && 十六色为空
			if (hidedata_textList.includes('标准16色') && activeProduct.value.b16c.length == 0) {
				errorStr = errorStr + '请选择标准16色<br/>';
			}
			//如果包含标准26色 && 标准26色为空
			if (hidedata_textList.includes('标准26色') && activeProduct.value.b26c.length == 0) {
				errorStr = errorStr + '请选择标准26色<br/>';
			}
			//如果包含基牙牙色 && 基牙牙色为空
			if (hidedata_textList.includes('基牙牙色') && activeProduct.value.jbys.length == 0) {
				errorStr = errorStr + '请选择基牙牙色<br/>';
			}
			//如果包含树脂牙比色 && 树脂牙比色为空
			if (hidedata_textList.includes('树脂牙比色') && activeProduct.value.szybs.length == 0) {
				errorStr = errorStr + '请选择树脂牙比色<br/>';
			}
		}

		//verificationList中有  校验设计要求
		if (verificationList.includes('设计要求')) {
			//如果包含颈缘要求 && 颈缘要求为空
			if (hidedata_textList.includes('颈缘要求') && activeProduct.value.jyyq.length == 0) {
				errorStr = errorStr + '请选择颈缘要求<br/>';
			}
			//如果包含咬颌要求 && 咬颌要求为空
			if (hidedata_textList.includes('咬颌要求') && activeProduct.value.yhyq.length == 0) {
				errorStr = errorStr + '请选择咬颌要求<br/>';
			}
			//如果包含就位要求 &&就位要求为空
			if (hidedata_textList.includes('就位要求') && activeProduct.value.jwyq.length == 0) {
				errorStr = errorStr + '请选择就位要求<br/>';
			}
		}

		//如果有内容 显示提示
		if (errorStr) {
			ElMessage.error({
				message: errorStr,
				dangerouslyUseHTMLString: true,
				type: 'error'
			});
			return false;
		}
		return true;
	};

	//提交时校验多个产品
	const productAllSingleVerification = () => {
		//提示字符串
		let errorStr = '';

		//循环所有产品集合
		for (let i = 0; i < ProductDataItmes.value.length; i++) {
			const item = ProductDataItmes.value[i];

			//获取要校验的内容
			let verificationList = activeProduct.value.choosedata_text ? activeProduct.value.choosedata_text.split(',') : [];

			//获取需要校验内容对应的字段
			let hidedata_textList = item.hidedata_text ? item.hidedata_text.split(',') : [];

			//如果要校验的内容是空的 不需要校验
			if (verificationList.length == 0) {
				continue;
			}

			//verificationList中有牙位  校验牙位
			if (verificationList.includes('牙位')) {
				//没有选择牙位 提示
				if (!item.single_crown && !item.multiple_crown) {
					//将提示内容 添加到提示字符串中
					errorStr = errorStr + '【' + item.title + '】请选择牙位<br/>';
				}
			}

			//verificationList中有  校验产品颜色
			if (verificationList.includes('产品颜色')) {
				//如果包含十六色 && 十六色为空
				if (hidedata_textList.includes('标准16色') && item.b16c.length == 0) {
					errorStr = errorStr + '【' + item.title + '】请选择标准16色<br/>';
				}
				//如果包含标准26色 && 标准26色为空
				if (hidedata_textList.includes('标准26色') && item.b26c.length == 0) {
					errorStr = errorStr + '【' + item.title + '】请选择标准26色<br/>';
				}
				//如果包含基牙牙色 && 基牙牙色为空
				if (hidedata_textList.includes('基牙牙色') && item.jbys.length == 0) {
					errorStr = errorStr + '【' + item.title + '】请选择基牙牙色<br/>';
				}
				//如果包含树脂牙比色 && 树脂牙比色为空
				if (hidedata_textList.includes('树脂牙比色') && item.szybs.length == 0) {
					errorStr = errorStr + '【' + item.title + '】请选择树脂牙比色<br/>';
				}
			}

			//verificationList中有  校验设计要求
			if (verificationList.includes('设计要求')) {
				//如果包含颈缘要求 && 颈缘要求为空
				if (hidedata_textList.includes('颈缘要求') && item.jyyq.length == 0) {
					errorStr = errorStr + '【' + item.title + '】请选择颈缘要求<br/>';
				}
				//如果包含咬颌要求 && 咬颌要求为空
				if (hidedata_textList.includes('咬颌要求') && item.yhyq.length == 0) {
					errorStr = errorStr + '【' + item.title + '】请选择咬颌要求<br/>';
				}
				//如果包含就位要求 &&就位要求为空
				if (hidedata_textList.includes('就位要求') && item.jwyq.length == 0) {
					errorStr = errorStr + '【' + item.title + '】请选择就位要求<br/>';
				}
			}
		}

		//如果有内容 显示提示
		if (errorStr) {
			ElMessage.error({
				message: errorStr,
				dangerouslyUseHTMLString: true,
				type: 'error'
			});
			return false;
		}
		return true;
	};

	// 字符串转数组
	function stringtoArray(data) {
		if (!data) return [];
		return (
			data
				.split(',')
				.map((item) => Number(item))
				.filter(Boolean) || []
		);
	}

	//附件要求
	const attachmentRequire = ref([]);
	//获取附件要求列表
	const sendAttachmentRequire = async () => {
		let res = await getAttachmentRequire();
		attachmentRequire.value = res.data;
		attachmentRequire.value.forEach(async (item, index) => {
			const res = await getAttachmentRequireDetail({ fitting_cate_id: item.id });
			attachmentRequire.value[index] = {
				...attachmentRequire.value[index],
				detailList: res.data.map((itemdeital) => {
					return {
						...itemdeital,
						num: 0
					};
				})
			};
		});
	};

	//七牛云
	const QiniuToken = ref('');

	//获取七牛云token
	const getQiniuTokens = async () => {
		let res = await getQiniuToken();
		QiniuToken.value = res.data;
	};

	// 产品牙色照片七牛云上传参数
	const ProductUploadParams = (data) => {
		return {
			token: QiniuToken.value?.token,
			key: new Date().getTime() + '-' + data.name
		};
	};

	// 电子附件列表
	const uploadFileListEle = ref([]);

	// 随单移除文件
	const removeFile = (item, index) => {
		uploadFileList.value.splice(index, 1);
	};

	//获取预览stl文件组件ref
	const stlPreviewRef = ref(null);

	//预览stl文件
	const handlestlPreview = (item) => {
		stlPreviewRef.value.openDialog(item);
	};

	// 文件上传后钩子
	const ProductUploadSuccess = (res) => activeProduct.value?.images.push('https://oss.ykshuju.com/' + res.key);

	// 附件tabs当前激活的标签页
	const attachment = ref(1);

	// 附件表单ref
	const attachmentFormRef = ref('');

	// 随单附件列表
	const uploadFileList = ref([]);

	// 图片附件列表
	const attachmentimages = ref([]);

	//随单附件上传前钩子
	const beforeUpload = async (file) => {
		if (uploadFileList.value.length) {
			//判断上传的file name 是否已经在列表中 如果在 不上传 提示
			if (uploadFileList.value.some((item) => item.name === file.name)) {
				ElMessage.warning('该文件已存在');
				return false;
			}
		}
		await getQiniuToken();
	};

	// 附件上传成功钩子
	const attachmentUploadSuccess = (res, file) => {
		uploadFileList.value.push({
			name: file.name,
			url: `https://oss.ykshuju.com/${res.key}`,
			type: file.raw.type,
			size: file.size
		});
	};

	//监听表单参数 产品id 医院id 医生id 如果有一个有值就获取习惯
	watch(
		() => [OrderForm.value.hospital_id, OrderForm.value.doc_user_id, ProductDataItmes.value],
		async () => {
			if (!isMounted.value && route.query.type) return;
			getHabitItems();
		},
		{ deep: true } // 深度监听，确保对象内部的变化也能被检测到
	);

	//获取习惯
	const getHabitItems = async () => {
		//处理数据
		let data = {
			hospital_id: OrderForm.value.hospital_id,
			doctor_id: OrderForm.value.doc_user_id,
			product_id: ProductDataItmes.value.length ? ProductDataItmes.value.map((item) => item.id).join(',') : ''
		};
		let res = await getHabit(data);
		//把,替换换行符
		res.data = res.data.replace(/,/g, '\n');
		OrderForm.value.remark2 = res.data;
	};

	// 重置表单
	watch(
		route,
		() => {
			if (!route.query.orderid && !route.query.type) resetForm();
			SetOrderInfo();
		},
		{ deep: true }
	);

	// 表单重置
	const resetForm = () => {
		OrderFormRef.value.resetFields();
		OrderForm.value.order_sn = '';
		OrderForm.value.order_sn1 = '';
		OrderForm.value.box_num = '';
		OrderForm.value.design_no = '';
		OrderForm.value.HospitalSearch = '';
		OrderForm.value.hospital_id = '';
		OrderForm.value.DoctorSearch = '';
		OrderForm.value.doc_user_id = '';
		OrderForm.value.name = '';
		OrderForm.value.area_str = '';
		OrderForm.value.yw_str = '';
		OrderForm.value.type_status = 1;
		OrderForm.value.is_try = 0;
		OrderForm.value.try_str = '';
		OrderForm.value.user_id = '';
		OrderForm.value.block_code = '';
		OrderForm.value.remark = '';
		OrderForm.value.remark2 = '';
		OrderForm.value.is_check_in = 1;

		attachmentRequire.value = attachmentRequire.value.map((item) => ({
			...item,
			detailList: item.detailList.map((detailitem) => ({ ...detailitem, num: 0 }))
		}));

		attachmentimages.value = [];

		uploadFileList.value = [];

		uploadFileListEle.value = [];

		tabsActiveName.value = 0;

		attachment.value = 1;

		newProducts.value = false;

		OrderData.value = {};

		ProductDataItmes.value = [];

		//清除记录老的试戴类型
		oldTryType.value = '';

		//默认鼠标选中在第一个输入框上
		setTimeout(() => {
			document.querySelector('.el-input__inner').focus();
		}, 500);
	};

	//订单详情
	const OrderData = ref({});

	// 更新表单
	const updateForm = async () => {
		OrderFormRef.value.validate(async (vaild) => {
			if (vaild) {
				if (ProductDataItmes.value.length == 0) return ElMessage.error('请至少添加一件产品');
				const product = productAllSingleVerification();
				if (product) {
					const res = await SendUpdateForm({
						...getFormParams(),
						order_id: route.query.orderid,
						user_id: OrderData.value.user_id
					});
					if (res) {
						ElMessage.success('修改成功');
						resetForm();
						//返回上一页
						// router.go(-1);
						top.window.$('ul.nav-addtabs li.active').find('.fa-remove').trigger('click');
					}
				}
			}
		});
	};

	//更新表单并打印
	const updateFormAndPrint = async () => {
		// await componentRef.value.batchPrinting('2508611519');
		// return;
		OrderFormRef.value.validate(async (vaild) => {
			if (vaild) {
				if (ProductDataItmes.value.length == 0) return ElMessage.error('请至少添加一件产品');
				const product = productAllSingleVerification();
				if (product) {
					const res = await SendUpdateForm({
						...getFormParams(),
						order_id: route.query.orderid,
						user_id: OrderData.value.user_id
					});
					if (res) {
						let elM = ElMessage.success({
							duration: 0,
							message: '订单修改成功，正在打印确认单，请稍等...'
						});
						// 此处使用本地打印
						// const res1 = await componentRef.value.batchPrinting('4', [OrderForm.value.order_sn], 'deliveryNote');
						const res1 = await componentRef.value.batchPrinting(OrderData.value.order_sn);
						if (res1) {
							ElMessage.success({
								dangerouslyUseHTMLString: true,
								message: `<div style="font-size:16px">打印确认单成功</div>`,
								duration: 5000
							});
						}
						elM.close();
						resetForm();
						setTimeout(() => {
							//返回上一页
							// router.go(-1);
							top.window.$('ul.nav-addtabs li.active').find('.fa-remove').trigger('click');
						}, 1000);
					}
				}
			}
		});
	};

	// 获取表单参数
	const getFormParams = () => {
		return {
			is_complete: 1,
			...OrderForm.value,
			order_sn: OrderForm.value.order_sn ? OrderForm.value.order_sn : OrderForm.value.order_sn1 || '',
			items: ProductDataItmes.value.map((item) => {
				return {
					product_id: item.id,
					single_crown: JSON.stringify(stringtoArray(toothConversion(stringtoArray(item.single_crown)))),
					multiple_crown: JSON.stringify(groupConsecutiveNumbers(stringtoArray(item.multiple_crown)).map((item) => stringtoArray(toothConversion(item)))),
					b16c: item.b16c.join(','),
					b26c: item.b26c.join(','),
					jbys: item.jbys.join(','),
					szybs: item.szybs.join(','),
					yase_remark: item.yase_remark,
					jwyq: item.jwyq && item.jwyq.join(','),
					yhyq: item.yhyq && item.yhyq.join(','),
					jyyq: item.jyyq && item.jyyq.join(','),
					qtyq: item.qtyq,
					num: item.num,
					images: item.images && item.images.join(',')
				};
			}),

			fittings: attachmentRequire.value
				.map((item) => item.detailList)
				.flat()
				.map((item) => {
					return {
						fitting_id: item.id,
						num: item.num
					};
				}),

			file: JSON.stringify(uploadFileList.value),

			e_file: JSON.stringify(uploadFileListEle.value)
		};
	};

	// 订单信息赋值
	const SetOrderInfo = async () => {
		const res = await getOrderDetailData(route.query.orderid);
		OrderData.value = res?.data;

		if (res?.hospital_id) await getDoctorListData({ hospital_id: res?.data?.hospital_id });

		// 基本订单信息
		//回显不显示生产批号
		OrderForm.value.order_sn = '';
		//从新记录 修改时使用
		OrderForm.value.order_sn1 = res?.data?.order_sn;
		OrderForm.value.box_num = res?.data?.box_num;
		OrderForm.value.design_no = res?.data?.design_no;
		OrderForm.value.HospitalSearch = res?.data?.hospital?.title;
		OrderForm.value.hospital_id = res?.data?.hospital_id;
		OrderForm.value.DoctorSearch = res?.data?.docuser?.nickname;
		OrderForm.value.doc_user_id = res?.data?.doc_user_id;
		OrderForm.value.name = res?.data?.name;
		OrderForm.value.area_str = res?.data?.area_str;
		OrderForm.value.yw_str = res?.data?.yw_str;
		OrderForm.value.type_status = Number(res?.data?.type_status);
		OrderForm.value.is_try = Number(res?.data?.is_try);
		OrderForm.value.try_str = Number(res?.data?.try_str);
		OrderForm.value.user_id = res?.data?.user_id;
		OrderForm.value.block_code = res?.data?.block_code;
		OrderForm.value.remark = res?.data?.remark;
		OrderForm.value.remark2 = res?.data?.remark2;
		OrderForm.value.order_type = 1;
		OrderForm.value.is_check_in = 1;
		//赋值老的试戴类型
		oldTryType.value = Number(res?.data?.try_str);
		// 产品集合
		ProductDataItmes.value = res?.data?.items.map((item, index) => {
			return {
				...item.product,
				b16c: item.b16c ? item.b16c.split(',').map(Number) : [],
				b26c: item.b26c ? item.b26c.split(',').map(Number) : [],
				jbys: item.jbys ? item.jbys.split(',').map(Number) : [],
				szybs: item.szybs ? item.szybs.split(',').map(Number) : [],
				yase_remark: item.yase_remark,
				jwyq: item.jwyq ? item.jwyq.split(',').map((it) => Number(it)) : [],
				yhyq: item.yhyq ? item.yhyq.split(',').map((it) => Number(it)) : [],
				jyyq: item.jyyq ? item.jyyq.split(',').map((it) => Number(it)) : [],
				images: item.images.split(',').filter((it) => it && it),
				single_crown: item.single_crown_text,
				multiple_crown: item.multiple_crown_text,
				maxillary: false,
				qtyq: item.qtyq,
				num: item.num,
				tooth_position_key: '',
				tooth_left_up_key: '', //产品牙位左上快捷键
				tooth_left_down_key: '', //产品牙位左下快捷键
				tooth_right_up_key: '', //产品牙位右上快捷键
				tooth_right_down_key: '', //产品牙位右下快捷键
				yase_key: '', //牙色输入框快捷键
				//生成唯一值
				uid: Date.now().toString(36) + Math.random().toString(36).substr(2)
			};
		});
		activeProduct.value = ProductDataItmes.value[0];
		// 附件信息
		setTimeout(() => {
			attachmentRequire.value = attachmentRequire.value.map((item) => ({
				...item,
				detailList: item.detailList.map((detailitem) => ({
					...detailitem,
					num: res?.data?.fittings.find((fittingsitem) => detailitem.id === fittingsitem.fitting_id)?.num || 0
				}))
			}));
		}, 500);
		// 随单附件
		uploadFileList.value = JSON.parse(res?.data?.file) || [];
		uploadFileListEle.value = res?.data?.new_efile || JSON.parse(res?.data?.e_file) || [];
		// 将生命周期是否已经执行设置为true
		setTimeout(() => (isMounted.value = true), 1000);
		console.log(activeProduct.value);
	};

	// 是否已经执行完生命周期
	const isMounted = ref(false);

	// 提交表单
	const sumbit = () => {
		OrderFormRef.value.validate(async (vaild) => {
			if (vaild) {
				if (ProductDataItmes.value.length == 0) return ElMessage.error('请至少添加一件产品');
				// const product = await productCollectionVerification();
				const product = productAllSingleVerification();
				// if (uploadFileListEle.value.length == 0) return ElMessage.error('请上传电子附件');
				if (product) {
					const res = await sumbitform({ ...getFormParams(), is_print: 1 });
					if (res) {
						ElMessage.success('订单提交成功');
						resetForm();
					}
				}
			}
		});
	};

	/**
	 * 提交并打印
	 *
	 */
	const sumbitAndPrint = async () => {
		//判断是否有选择的本地打印机 如果没有 弹窗选择打印机
		const isBdPrntItem = printStore.getBdPrintItem;
		if (!isBdPrntItem) {
			printDialogVisible.value = true;
			return;
		}

		OrderFormRef.value.validate(async (vaild) => {
			if (vaild) {
				if (ProductDataItmes.value.length == 0) return ElMessage.error('请至少添加一件产品');
				const product = productAllSingleVerification();
				if (product) {
					const res = await sumbitform({ ...getFormParams(), is_print: 1 });
					if (res) {
						let elM = ElMessage.success({
							duration: 0,
							message: '订单提交成功，正在打印确认单，请稍等...'
						});

						// 本地自定义模板打印 prPage
						// const res1 = await componentRef.value.batchPrinting('4', [res.data.order_sn], 'deliveryNote');

						//本地写死模板打印 locationPrint
						const res1 = await componentRef.value.batchPrinting(res.data.order_sn);

						if (res1) {
							ElMessage.success({
								dangerouslyUseHTMLString: true,
								message: `<div style="font-size:16px">打印确认单成功</div>`,
								duration: 5000
							});
						}
						elM.close();
						resetForm();
					}
				}
			}
		});
	};
	// 用于存储单选项的 DOM 元素
	const radioItemRefs = reactive([]);

	// 存储每个 el-radio 的 ref
	const setRadioRef = (el, index) => {
		if (el && el.$el) {
			radioItemRefs[index] = el.$el; // 获取真实 DOM
		}
	};

	// 输入框的键盘事件处理
	const handleDialogInputKeydown = (event) => {
		if (event.key === 'ArrowDown') {
			event.preventDefault(); // 阻止默认行为
			// 确保 ProductData 有数据后再尝试聚焦
			if (ProductData.value && ProductData.value.length > 0) {
				nextTick(() => {
					if (radioItemRefs[0]) {
						radioItemRefs[0].focus(); // 将焦点移动到第一个单选项
						radioItemRefs[0].click();
					}
				});
			}
		}
	};

	// 处理键盘事件
	const handleRadioKeydown = (event) => {
		const key = event.key;
		let index = radioItemRefs.findIndex((item) => item.contains(document.activeElement));

		if (key === 'ArrowDown') {
			event.preventDefault();
			const nextIndex = (index + 1) % radioItemRefs.length;
			radioItemRefs[nextIndex].focus(); // 移动到下一个单选项
			radioItemRefs[nextIndex].click(); // 移动到下一个单选项
		} else if (key === 'ArrowUp') {
			event.preventDefault();
			if (index > 0) {
				const prevIndex = (index - 1 + radioItemRefs.length) % radioItemRefs.length;
				radioItemRefs[prevIndex].focus(); // 移动到上一个单选项
				radioItemRefs[prevIndex].click(); // 移动到上一个单选项
			} else {
				dialogInput.value.focus(); // 如果在第一个项，返回输入框
			}
		} else if (key === 'Enter') {
			event.preventDefault();
			addProduct();
		}
	};

	//整个页面的输入框
	const handleKeydown = async (event) => {
		// 获取所有具有 'focInput' 类的输入框
		let nodeList = document.querySelectorAll('.focInput');
		let nodeArray = Array.from(nodeList); // 将 NodeList 转换为数组

		// 获取当前聚焦的输入框索引
		let currentIndex = nodeArray.findIndex((el) => el === document.activeElement || el.contains(document.activeElement));
		console.log('currentIndex', currentIndex);
		// 监听右箭头键 和 回车
		if (event.key === 'ArrowRight' || event.key === 'Enter') {
			event.preventDefault(); // 阻止默认行为

			//如果回车事件 并且 按钮是输入产品快捷键
			if (event.key === 'Enter' && currentIndex == 13) {
				//查找产品
				await productKeyChange();
				nodeList = document.querySelectorAll('.focInput');
				nodeArray = Array.from(nodeList); // 将 NodeList 转换为数组

				// 获取当前聚焦的输入框索引
				currentIndex = nodeArray.findIndex((el) => el === document.activeElement || el.contains(document.activeElement));
				//1秒之后 清空值
				setTimeout(() => {
					event.target.value = '';
				}, 1000);
				// return;
			}

			//如果是回车事件 并且 按钮是牙位快捷键
			if (event.key == 'Enter' && currentIndex == 14) {
				//拿到输入框的值
				activeProduct.value.tooth_position_key = event.target.value;
				//1秒之后 清空值
				setTimeout(() => {
					event.target.value = '';
				}, 1000);
				// return;
			}

			//如果是回车事件 并且 按钮是左上牙位快捷键
			if (event.key == 'Enter' && currentIndex == 15) {
				//拿到输入框的值
				activeProduct.value.tooth_left_up_key = event.target.value;
				//1秒之后 清空值
				setTimeout(() => {
					event.target.value = '';
				}, 1000);
				// return;
			}

			//如果是回车事件 并且 按钮是右上牙位快捷键
			if (event.key == 'Enter' && currentIndex == 16) {
				//拿到输入框的值
				activeProduct.value.tooth_right_up_key = event.target.value;
				//1秒之后 清空值
				setTimeout(() => {
					event.target.value = '';
				}, 1000);
				// return;
			}

			//如果是回车事件 并且 按钮是左下牙位快捷键
			if (event.key == 'Enter' && currentIndex == 17) {
				//拿到输入框的值
				activeProduct.value.tooth_left_down_key = event.target.value;
				//1秒之后 清空值
				setTimeout(() => {
					event.target.value = '';
				}, 1000);
				// return;
			}

			//如果是回车事件 并且 按钮右下牙位快捷键
			if (event.key == 'Enter' && currentIndex == 18) {
				//拿到输入框的值
				activeProduct.value.tooth_right_down_key = event.target.value;
				//1秒之后 清空值
				setTimeout(() => {
					event.target.value = '';
				}, 1000);
				// return;
			}

			//如果是回车事件 并且 按钮是牙色快捷键
			if (event.key == 'Enter' && currentIndex == 19) {
				activeProduct.value.yase_key = event.target.value;
				//查询
				handleYaseKeyChange(activeProduct.value);
				setTimeout(() => {
					event.target.value = '';
				}, 1000);
				// return;
			}

			//如果是回车事件 并且按钮是提交及打印 或者 是提交 不要去下一个索引
			if ((event.key === 'Enter' && nodeList.length - 2 == currentIndex) || (event.key === 'Enter' && nodeList.length - 1 == currentIndex)) {
				return;
			}

			let nextIndex = '';

			//如果currentIndex == 5 跳七个
			if (currentIndex == 5) {
				nextIndex = (currentIndex + 8) % nodeArray.length;
			} else {
				// 计算下一个输入框的索引
				nextIndex = (currentIndex + 1) % nodeArray.length;
			}

			// 如果找到下一个输入框，则聚焦
			if (nodeArray[nextIndex]) {
				// 对于 Element Plus 的 el-autocomplete 和 el-select 组件，需要特殊处理
				if (nodeArray[nextIndex].classList.contains('el-autocomplete') || nodeArray[nextIndex].classList.contains('el-select') || nodeArray[nextIndex].classList.contains('el-input')) {
					let inputElement = nodeArray[nextIndex].querySelector('input');
					//如果当前输入框禁用 跳到下一个
					if (inputElement.disabled) {
						inputElement = nodeArray[nextIndex + 1].querySelector('input');
					}
					if (inputElement) {
						inputElement.focus(); // 聚焦到内部 input 元素
					}
				} else {
					nodeArray[nextIndex].focus(); // 移动到下一个输入框
				}
			}
		}

		//监听左箭头
		if (event.key === 'ArrowLeft') {
			event.preventDefault(); // 阻止默认行为
			let nextIndex = '';
			if (currentIndex > 0) {
				//如果currentIndex == 5 跳七个
				if (currentIndex == 13) {
					nextIndex = (currentIndex - 8 + nodeArray.length) % nodeArray.length;
				} else {
					// 计算上一个输入框的索引
					nextIndex = (currentIndex - 1 + nodeArray.length) % nodeArray.length;
				}
			}

			// 如果找到下一个输入框，则聚焦
			if (nodeArray[nextIndex]) {
				// 对于 Element Plus 的 el-autocomplete 和 el-select 组件，需要特殊处理
				if (nodeArray[nextIndex].classList.contains('el-autocomplete') || nodeArray[nextIndex].classList.contains('el-select') || nodeArray[nextIndex].classList.contains('el-input')) {
					let inputElement = nodeArray[nextIndex].querySelector('input');
					//如果当前输入框禁用 跳到下一个
					if (inputElement.disabled) {
						inputElement = nodeArray[nextIndex - 1].querySelector('input');
					}
					if (inputElement) {
						inputElement.focus(); // 聚焦到内部 input 元素
					}
				} else {
					nodeArray[nextIndex].focus(); // 移动到下一个输入框
				}
			}
		}

		//监听shift 键 聚焦到输入产品快捷键
		if (event.key == 'Shift') {
			event.preventDefault(); // 阻止默认行为
			let nextIndex = 13;
			// 如果找到下一个输入框，则聚焦
			if (nodeArray[nextIndex]) {
				// 对于 Element Plus 的 el-autocomplete 和 el-select 组件，需要特殊处理
				if (nodeArray[nextIndex].classList.contains('el-autocomplete') || nodeArray[nextIndex].classList.contains('el-select') || nodeArray[nextIndex].classList.contains('el-input')) {
					let inputElement = nodeArray[nextIndex].querySelector('input');
					//如果当前输入框禁用 跳到下一个
					if (inputElement.disabled) {
						inputElement = nodeArray[nextIndex - 1].querySelector('input');
					}
					if (inputElement) {
						inputElement.focus(); // 聚焦到内部 input 元素
					}
				} else {
					nodeArray[nextIndex].focus(); // 移动到下一个输入框
				}
			}
		}

		//监听下箭头 让浏览器向下滚动
		if (event.key == 'ArrowDown') {
			if (currentIndex == 3 || currentIndex == 4) {
				return;
			}
			window.scrollBy(0, 100);
		}

		//箭头上箭头 让浏览器向上滚动
		if (event.key == 'ArrowUp') {
			if (currentIndex == 3 || currentIndex == 4) {
				return;
			}
			window.scrollBy(0, -100);
		}
	};

	// 处理Tab键在textarea中的行为
	const handleTab = (event, key) => {
		const textarea = event.target;
		const start = textarea.selectionStart;
		const end = textarea.selectionEnd;
		const value = textarea.value;

		// 插入制表符和换行符
		const tabWithNewline = '\n';
		textarea.value = value.substring(0, start) + tabWithNewline + value.substring(end);

		// 设置光标位置到制表符和换行符之后
		const newCursorPos = start + tabWithNewline.length;
		textarea.setSelectionRange(newCursorPos, newCursorPos);

		// 更新绑定的值
		OrderForm.value[key] = textarea.value;

		event.preventDefault();
	};

	//打印机配置弹窗
	const printDialogVisible = ref(false);

	// 默认选中的打印机按钮
	const printerName = ref(0);

	// 选中的打印机
	const selectprinter = ref('');

	function getImageUrl(name) {
		return new URL(`../../assets/icon/${name}.png`, import.meta.url).href;
	}

	//打印机类型列表
	const printerNameList = ref([
		{
			id: 1,
			name: '确认单打印机',
			icon: getImageUrl('dispatchPrinter'),
			selectprinter: ''
		}
		// {
		// 	id: 2,
		// 	name: '制卡打印机',
		// 	icon: getImageUrl('cardPrinter')
		// },
		// {
		// 	id: 3,
		// 	name: '标签打印机',
		// 	icon: getImageUrl('tagPrinter')
		// }
	]);

	//初始化打印机配置
	const printList = ref([]);
	// 初始化
	const init = () => {
		printList.value = [];
		let LODOP = getLodop();
		let counter = LODOP.GET_PRINTER_COUNT();
		for (let i = 0; i < counter; i++) {
			printList.value.push({
				name: LODOP.GET_PRINTER_NAME(i),
				value: i
			});
		}
		printStore.setPrintList(printList.value);
	};

	// 打印机类型选择事件
	const selectPrinterType = (item) => {
		printerName.value = item.id;
		printStore.setPrintListItem(item);
	};

	// 打印机选择
	const printerSelect = (item) => {
		selectprinter.value = item.name;
		printStore.setBdPrintItem(item);
	};

	//选择打印配置确认
	const handlePrint = () => {
		//校验有没有填
		if (!printerName.value) {
			ElMessage.error('请选择打印机类型');
			return;
		}
		if (!selectprinter.value) {
			ElMessage.error('请选择打印机');
			return;
		}
		printDialogVisible.value = false;
	};

	onMounted(async () => {
		//获取试戴类型
		await getTry_strData();
		//获取标准16色
		await getColor16Data();
		//获取标准26色
		await getColor26Data();
		//获取基牙牙色
		await getAbutmentColor();
		//获取就位要求
		await getPositionRequire();
		//获取咬颌要求
		await getBiteMouthRequire();
		//获取颈缘要求
		await getNeckRequire();
		// 获取树脂牙比色列表;
		await getResinToothColorimetry();
		//获取七牛云token
		await getQiniuTokens();
		//获取附件要求
		await sendAttachmentRequire();

		if (route.query.orderid && ['detail', 'update'].includes(route.query.type)) {
			SetOrderInfo();
		}

		//默认鼠标选中在第一个输入框上
		setTimeout(() => {
			document.querySelector('.el-input__inner').focus();
		}, 500);

		nextTick(() => {
			//禁用tabs 聚焦事件
			const tabItems = document.querySelectorAll('.el-tabs__item');
			tabItems.forEach((item) => {
				item.setAttribute('tabindex', '-1'); // 禁止通过Tab聚焦
			});

			//禁用inputNumber聚焦事件
			setTimeout(() => {
				const inputNumbers = document.querySelectorAll('.inputNumber .el-input .el-input__wrapper .el-input__inner');
				inputNumbers.forEach((item) => {
					item.setAttribute('tabindex', '-1'); // 禁止通过Tab聚焦
				});
				const uploadFileList = document.querySelectorAll('.el-upload');
				uploadFileList.forEach((item) => {
					item.setAttribute('tabindex', '-1'); // 禁止通过Tab聚焦
				});
			}, 1000);
		});
	});
</script>
<style lang="scss" scoped>
	.index {
		height: 100%;
		// min-height: 100vh;
		display: flex;
		flex-direction: column;
		padding: 5px 20px 0 20px;
		background-color: white;
		position: relative;
		box-sizing: border-box;
	}

	.elform {
		display: flex;
		flex-direction: column;
		// gap: 10px;
	}

	.title {
		font-size: 20px;
		font-weight: bolder;
		user-select: none;
	}

	:deep(.el-form-item__content) {
		line-height: normal;
	}

	:deep(.el-upload--picture-card) {
		border: none !important;
	}

	:deep(.el-form-item) {
		margin-bottom: 0;
	}

	:deep(.editProduct .el-form-item) {
		margin-bottom: 20px;
	}

	:deep(.el-form-item__label) {
		margin-bottom: 0;
	}

	:deep(.el-form-item--large) {
		margin-bottom: 0;
	}

	:deep(.el-input),
	:deep(.el-select) {
		height: 30px;
	}

	:deep(.el-select__wrapper) {
		min-height: 30px;
	}

	:deep(.el-checkbox.el-checkbox--large) {
		height: 30px;
	}

	.productBox {
		margin-top: 5px;
		display: grid;
		grid-gap: 20px;

		.product_title {
			display: flex;
			align-items: center;
			justify-content: space-between;

			.title_right {
				display: flex;
				gap: 10px;
			}
		}
		//隐藏滚动条
		::-webkit-scrollbar {
			display: none !important;
		}
		.editProduct {
			width: 100%;
			height: 350px;
			border: 1px dashed #e8e8e8;
			overflow-y: scroll;
			padding: 10px;
			box-sizing: border-box;

			&-item {
				border: 1px dashed #dee2e6;
				padding: 10px;
				border-radius: 5px;
			}

			.flexstart {
				justify-content: center;
			}

			.BtnBox {
				display: flex;
				align-items: center;
				gap: 10px;

				&-btn {
					width: 100px;
					height: 30px;
					background-color: transparent;
					border: solid 1px rgba(0, 0, 0, 0.2);
					color: black;
					display: flex;
					justify-content: center;
					align-items: center;
					border-radius: 5px;
					cursor: pointer;
					font-size: 14px;
				}

				.singleCrown {
					background-color: #ff9e00;
					border: solid 1px #ff9e00;
					color: white;
				}

				.winTheChampionshipInARow {
					background-color: rgb(127, 168, 255);
					border: solid 1px rgb(127, 168, 255);
					color: white;
				}
			}

			:deep(.tooth_position_box .el-form-item__content) {
				display: flex;
				flex-direction: column;
				align-items: flex-start !important;
				// height: 30px;
			}
			.tooth_position_label {
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: space-between;
				font-size: 14px;
				color: #606266;

				p {
					min-width: 100px;
				}

				.tooth_position_input {
					width: 100%;
					height: 30px;
					outline: none;
					padding: 1px 15px;
					border-radius: 4px;
					border: none;
					border: 1px solid #dcdfe6;
					color: #606266;
				}

				.tooth_position_input:focus {
					border: 1px solid #409eff;
				}
			}
		}

		&-itemimages {
			display: grid;
			grid-template-columns: repeat(5, 1fr);
			grid-gap: 10px;

			:deep(.el-upload--picture-card) {
				width: 100px;
				height: 100px;
			}

			&-img {
				width: 100px;
				height: 100px;
				border-radius: 5px;
				position: relative;
				transition: all 0.3s ease;
				user-select: none;

				.deleteicon {
					position: absolute;
					right: -10px;
					top: -10px;
					width: 15px;
					height: 15px;
					cursor: pointer;
				}

				&:hover {
					cursor: pointer;
				}
			}
		}

		.product_list {
			border: 1px dashed #eee;
			width: 100%;
			height: 280px;
			padding: 5px;
			box-sizing: border-box;

			.header {
				width: 100%;
				height: 20px;
				display: flex;
				align-items: center;
				justify-content: space-between;
				font-size: 14px;
			}
			.product_list_c {
				height: calc(100% - 20px);
				overflow: auto;
			}

			.product_list_content {
				height: min-content;
				min-height: 50px;
				display: flex;
				align-items: center;
				justify-content: space-around;
				font-size: 14px;
				cursor: pointer;
				position: relative;
				margin-bottom: 10px;
			}

			.product_list_content_active {
				border: 1px solid #409eff;
				border-radius: 4px;
			}

			.del {
				position: absolute;
				right: 5px;
			}

			.num {
				max-width: 100px;
				width: 100px;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.type {
				max-width: 200px;
				width: 200px;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.yawei {
				max-width: 200px;
				width: 200px;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.yase {
				max-width: 200px;
				width: 200px;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
			}

			.yaoqiu {
				max-width: 200px;
				width: 200px;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
			}

			.yaseimg {
				max-width: 200px;
				width: 200px;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.jiage {
				max-width: 200px;
				width: 200px;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}

	:deep(.colorUpload .el-upload-dragger) {
		width: 100px;
		height: 100px;
		padding: 0 !important;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.uploadfile {
		display: flex;
		flex-direction: column;
		gap: 10px;

		:deep(.uploadele .el-upload-dragger) {
			width: 100%;
			height: 100px;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
		}

		:deep(.supload .el-upload) {
			width: 100px;
			height: 100px;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;

			.el-upload-dragger {
				width: 100%;
			}
		}

		.productBoxlist {
			height: 78px;
			padding: 10px;
			border: 1px dashed #dee2e6;
			display: grid;
			grid-template-columns: 1fr auto;
			align-items: center;
			border-radius: 5px;
			gap: 10px;
			cursor: pointer;

			&:hover {
				border: 1px dashed #98a6ad;
			}

			&-left {
				display: flex;
				gap: 10px;
			}

			&-right {
				cursor: pointer;
				display: flex;
				align-self: center;
				font-size: 14px;
				gap: 3px;
			}

			&-img {
				width: 70px;
				height: 70px;
				border-radius: 5px;
				object-fit: cover;
			}

			&-type {
				width: 70px;
				height: 70px;
				border-radius: 5px;
				display: flex;
				justify-content: center;
				align-items: center;
				background-color: #f5f5f5;
			}

			&-info {
				display: flex;
				flex-direction: column;
				gap: 5px;
			}
		}
	}

	.addproduct {
		height: 90px;
		background-color: #fff;
		border: 1px dashed #dee2e6;
		display: flex;
		justify-content: center;
		align-items: center;
		gap: 10px;
		cursor: pointer;
		color: #6c757d;
		margin: 10px 0;
		border-radius: 5px;

		&:hover {
			border: 1px dashed #98a6ad;
		}
	}

	:deep(.el-tabs__new-tab) {
		border: none;
		pointer-events: none;
	}

	.emptybox {
		width: 100%;
		display: flex;
		flex-direction: column;
		gap: 10px;
		align-items: center;
		margin-top: 100px;
		cursor: pointer;
		user-select: none;

		&-icon {
			width: 100px;
			height: 100px;
			user-select: none;
		}

		&-text {
			font-size: 14px;
			color: rgba(0, 0, 0, 0.5);
		}
	}

	.productdialog {
		display: flex;
		gap: 10px;
		height: 500px;
		margin-bottom: 20px;

		&-left {
			height: 500px;
			overflow-y: scroll;

			&::-webkit-scrollbar {
				display: none;
			}
		}
		&-right {
			flex: 1;
			height: 500px;
			overflow-y: scroll;

			&::-webkit-scrollbar {
				width: 3px;
			}

			&::-webkit-scrollbar-thumb {
				background-color: rgba(0, 0, 0, 0.1);
				border-radius: 10rem;
			}

			:deep(.el-radio-group) {
				display: grid;
				grid-gap: 10px;

				.el-radio {
					width: 100%;
					margin: 0;
					padding: 0 10px;
				}
			}
		}

		&-footer {
			width: 100%;
			display: flex;
			justify-content: flex-end;
			align-items: center;
		}
	}

	.dialogsearch {
		padding: 10px 0;
		display: flex;
		margin-left: 210px;
		align-items: center;
		gap: 10px;
	}

	.sumbit {
		width: 100%;
		height: 30px;
		background-color: white;
		display: flex;
		justify-content: center;
		align-items: center;
		position: sticky;
		bottom: 0;
		padding: 20px 0;
		z-index: 1000;
		box-sizing: unset;

		&-btn {
			width: 10%;
			height: 30px;
			margin-left: 5px;
		}
	}

	.selectbox {
		height: 500px;
		flex: 1;
		display: flex;

		&-left {
			width: 200px;
			padding: 10px 10px 10px 0;
			border-right: 1px solid #e8e8e8;
			display: flex;
			flex-direction: column;
			gap: 10px;

			.printer {
				display: flex;
				align-items: center;
				gap: 10px;
				padding: 5px 10px;
				cursor: pointer;
				border-radius: 5px;
				border: 1px solid transparent;
				background-color: #f2f6fc;
				color: #303133;

				.icon {
					width: 25px;
					height: 25px;
				}

				.title {
					font-size: 14px;
				}

				&:hover {
					border: 1px solid #409eff;
				}
			}

			.activeprinter {
				background-color: #d9ecff;
				border: 1px solid #409eff;
			}
		}

		&-right {
			flex: 1;
			padding: 10px;

			.rightbox {
				display: grid;
				grid-template-columns: repeat(3, 1fr);
				grid-gap: 10px;
			}

			.printercard {
				height: 100px;
				border: 1px solid #e8e8e8;
				background-color: white;
				position: relative;
				border-radius: 5px;
				display: flex;
				justify-content: center;
				align-items: center;
				cursor: pointer;

				.selectactive {
					position: absolute;
					right: 3px;
					top: 3px;
					border: 6px solid transparent;
					border-top-color: #33cc99;
					border-right-color: #33cc99;
					border-top-right-radius: 3px;
				}

				.icon {
					width: 20px;
					height: 20px;
					position: absolute;
					right: 5px;
					top: 5px;
				}

				&-item {
					padding: 10px;
					display: flex;
					align-items: center;
					gap: 10px;
					color: #303133;
					font-size: 14px;
				}

				&:hover {
					border: 1px solid #409eff;
				}
			}

			.active {
				background-color: #d9ecff;
				border: 1px solid #409eff;
			}
		}
	}

	.compo {
		position: absolute;
		top: -10000px;
		// top: 0;
	}
</style>
